package com.itheima.controller.ex;

import com.itheima.controller.vo.ResultVo;
import com.sun.org.apache.xml.internal.res.XMLErrorResources_tr;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;

/**
 * @author xiangjun.deng
 * email 17670934918dxj@sina.com
 * @date 2021/8/24 21:33
 * @desc
 */
@Component
@ControllerAdvice
public class ExceptionParamValidate {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    private ResultVo handleException(Exception e) {
        StringBuilder sb = new StringBuilder();
        ResultVo resultVo = new ResultVo();
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;

            List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors();
            sb.append("{");
            for (int i = 0; i < fieldErrors.size(); i++) {

                if (i == fieldErrors.size() - 1) {
                    sb.append(fieldErrors.get(i).getDefaultMessage());
                } else {
                    sb.append(fieldErrors.get(i).getDefaultMessage() + ",");
                }

            }
        }
        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException exception = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
            for (ConstraintViolation<?> constraintViolation : constraintViolations) {
                String message = constraintViolation.getMessage();
                sb.append(message);
            }

        }
        resultVo.setCode(0);
        resultVo.setData(null);
        resultVo.setMsg(sb.toString());
        resultVo.setFlag(false);
        return resultVo;

    }


}
